#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file rest_api.py
@brief 电机控制REST API接口
@details 提供HTTP REST API接口，供其他程序通过网络请求控制电机
@author zhang33
@date 2025-09-05
"""

import logging
import json
from typing import Dict, Any, Optional
from flask import Flask, request, jsonify
from flask_cors import CORS

from .motor_api import MotorAPI

logger = logging.getLogger(__name__)


class MotorRESTAPI:
    """
    @brief 电机控制REST API类
    @details 提供HTTP REST API接口控制电机
    """
    
    def __init__(self, config_file: str = "config/serial_config.json", 
                 host: str = "0.0.0.0", port: int = 5000):
        """
        @brief 初始化REST API
        @param config_file 配置文件路径
        @param host 服务器地址
        @param port 服务器端口
        """
        self.motor_api = MotorAPI(config_file)
        self.host = host
        self.port = port
        
        # 创建Flask应用
        self.app = Flask(__name__, static_folder='../web', static_url_path='')
        CORS(self.app)  # 允许跨域请求
        
        # 注册路由
        self._register_routes()
        
        logger.info(f"REST API初始化完成 - 地址: {host}:{port}")
    
    def _register_routes(self) -> None:
        """
        @brief 注册API路由
        """
        # 连接管理
        self.app.route('/api/connect', methods=['POST'])(self._connect)
        self.app.route('/api/disconnect', methods=['POST'])(self._disconnect)
        self.app.route('/api/status', methods=['GET'])(self._get_status)
        self.app.route('/api/test', methods=['GET'])(self._test_connection)
        self.app.route('/api/test-serial', methods=['POST'])(self._test_serial_config)
        
        # 串口终端相关接口
        self.app.route('/api/serial/send', methods=['POST'])(self._send_serial_command)
        self.app.route('/api/serial/receive', methods=['GET'])(self._receive_serial_data)
        self.app.route('/api/serial/start-terminal', methods=['POST'])(self._start_serial_terminal)
        self.app.route('/api/serial/stop-terminal', methods=['POST'])(self._stop_serial_terminal)
        
        # UART串口日志监控相关接口
        self.app.route('/api/uart/connect', methods=['POST'])(self._connect_uart)
        self.app.route('/api/uart/disconnect', methods=['POST'])(self._disconnect_uart)
        self.app.route('/api/uart/send', methods=['POST'])(self._send_uart_command)
        self.app.route('/api/uart/receive', methods=['GET'])(self._receive_uart_data)
        self.app.route('/api/uart/start-monitor', methods=['POST'])(self._start_uart_monitor)
        self.app.route('/api/uart/stop-monitor', methods=['POST'])(self._stop_uart_monitor)
        self.app.route('/api/uart/config', methods=['GET'])(self._get_uart_config)
        self.app.route('/api/uart/config', methods=['POST'])(self._set_uart_config)
        self.app.route('/api/uart/test', methods=['POST'])(self._test_uart_config)
        
        # 电机控制
        self.app.route('/api/motor/start', methods=['POST'])(self._start_motors)
        self.app.route('/api/motor/stop', methods=['POST'])(self._stop_motors)
        self.app.route('/api/motor/emergency_stop', methods=['POST'])(self._emergency_stop)
        self.app.route('/api/motor/speed', methods=['POST'])(self._set_speed)
        self.app.route('/api/motor/phase_learning', methods=['POST'])(self._phase_learning)
        self.app.route('/api/motor/reset', methods=['POST'])(self._reset_system)
        
        # 便捷控制
        self.app.route('/api/motor/forward', methods=['POST'])(self._move_forward)
        self.app.route('/api/motor/backward', methods=['POST'])(self._move_backward)
        self.app.route('/api/motor/turn_left', methods=['POST'])(self._turn_left)
        self.app.route('/api/motor/turn_right', methods=['POST'])(self._turn_right)
        self.app.route('/api/motor/differential', methods=['POST'])(self._differential_move)
        
        # 监控管理
        self.app.route('/api/monitor/start', methods=['POST'])(self._start_monitoring)
        self.app.route('/api/monitor/stop', methods=['POST'])(self._stop_monitoring)
        self.app.route('/api/monitor/status', methods=['GET'])(self._get_monitor_status)
        
        # 数据记录
        self.app.route('/api/log/start', methods=['POST'])(self._start_logging)
        self.app.route('/api/log/stop', methods=['POST'])(self._stop_logging)
        self.app.route('/api/log/status', methods=['GET'])(self._get_log_status)
        self.app.route('/api/log/test', methods=['POST'])(self._test_logging)
        
        # 配置管理
        self.app.route('/api/config/serial', methods=['GET', 'POST'])(self._serial_config)
        self.app.route('/api/config/motor', methods=['GET', 'POST'])(self._motor_config)
        self.app.route('/api/config/logging', methods=['GET', 'POST'])(self._logging_config)
        self.app.route('/api/config/logging/options', methods=['GET'])(self._get_logging_options)
        self.app.route('/api/config/save', methods=['POST'])(self._save_config)
        self.app.route('/api/config/load', methods=['POST'])(self._load_config)
        
        # 扫描串口接口
        self.app.route('/api/scan-ports', methods=['GET'])(self._scan_ports)
        self.app.route('/api/ports', methods=['GET'])(self._scan_ports)  # 别名接口
        
        # 健康检查
        self.app.route('/api/health', methods=['GET'])(self._health_check)
        
        # 根路径 - 返回Web界面
        self.app.route('/', methods=['GET'])(self._web_interface)
    
    # ==================== 连接管理API ====================
    
    def _connect(self) -> Dict[str, Any]:
        """
        @brief 连接电机驱动器
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.connect()
            return {
                'success': success,
                'message': '连接成功' if success else '连接失败',
                'connected': self.motor_api.is_connected()
            }
        except Exception as e:
            logger.error(f"连接API异常: {e}")
            return {
                'success': False,
                'message': f'连接异常: {e}',
                'connected': False
            }
    
    def _disconnect(self) -> Dict[str, Any]:
        """
        @brief 断开连接
        @return Dict[str, Any] API响应
        """
        try:
            self.motor_api.disconnect()
            return {
                'success': True,
                'message': '断开连接成功',
                'connected': False
            }
        except Exception as e:
            logger.error(f"断开连接API异常: {e}")
            return {
                'success': False,
                'message': f'断开连接异常: {e}',
                'connected': self.motor_api.is_connected()
            }
    
    def _get_status(self) -> Dict[str, Any]:
        """
        @brief 获取连接状态
        @return Dict[str, Any] API响应
        """
        try:
            connected = self.motor_api.is_connected()
            motor_status = self.motor_api.get_motor_status() if connected else None
            motor_config = self.motor_api.get_motor_config()
            uart_connected = self.motor_api.is_uart_connected()
            
            return {
                'success': True,
                'connected': connected,
                'motor_status': motor_status,
                'motor_config': motor_config,
                'monitoring': self.motor_api.is_monitoring(),
                'logging': self.motor_api.is_logging(),
                'uart_connected': uart_connected,
                'uart_monitoring': uart_connected  # 如果UART连接了，就认为在监控
            }
        except Exception as e:
            logger.error(f"获取状态API异常: {e}")
            return {
                'success': False,
                'message': f'获取状态异常: {e}',
                'connected': False
            }
    
    def _test_connection(self) -> Dict[str, Any]:
        """
        @brief 测试连接
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.test_connection()
            return {
                'success': success,
                'message': '连接测试成功' if success else '连接测试失败',
                'connected': self.motor_api.is_connected()
            }
        except Exception as e:
            logger.error(f"测试连接API异常: {e}")
            return {
                'success': False,
                'message': f'测试连接异常: {e}',
                'connected': False
            }
    
    def _test_serial_config(self) -> Dict[str, Any]:
        """
        @brief 测试串口配置
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.test_serial_config()
            return {
                'success': success,
                'message': '串口配置测试成功' if success else '串口配置测试失败',
                'can_connect': success
            }
        except Exception as e:
            logger.error(f"串口配置测试API异常: {e}")
            return {
                'success': False,
                'message': f'串口配置测试异常: {e}',
                'can_connect': False
            }
    
    # ==================== 电机控制API ====================
    
    def _start_motors(self) -> Dict[str, Any]:
        """
        @brief 启动电机
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            left_speed = data.get('left_speed', 500)
            right_speed = data.get('right_speed', 500)
            
            success = self.motor_api.start_motors(left_speed, right_speed)
            return {
                'success': success,
                'message': '电机启动成功' if success else '电机启动失败',
                'left_speed': left_speed,
                'right_speed': right_speed
            }
        except Exception as e:
            logger.error(f"启动电机API异常: {e}")
            return {
                'success': False,
                'message': f'启动电机异常: {e}'
            }
    
    def _stop_motors(self) -> Dict[str, Any]:
        """
        @brief 停止电机
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.stop_motors()
            return {
                'success': success,
                'message': '电机停止成功' if success else '电机停止失败'
            }
        except Exception as e:
            logger.error(f"停止电机API异常: {e}")
            return {
                'success': False,
                'message': f'停止电机异常: {e}'
            }
    
    def _emergency_stop(self) -> Dict[str, Any]:
        """
        @brief 急停电机
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.emergency_stop()
            return {
                'success': success,
                'message': '电机急停成功' if success else '电机急停失败'
            }
        except Exception as e:
            logger.error(f"急停电机API异常: {e}")
            return {
                'success': False,
                'message': f'急停电机异常: {e}'
            }
    
    def _set_speed(self) -> Dict[str, Any]:
        """
        @brief 设置电机转速
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            left_speed = data.get('left_speed')
            right_speed = data.get('right_speed')
            
            success = self.motor_api.set_motor_speed(left_speed, right_speed)
            return {
                'success': success,
                'message': '转速设置成功' if success else '转速设置失败',
                'left_speed': left_speed,
                'right_speed': right_speed
            }
        except Exception as e:
            logger.error(f"设置转速API异常: {e}")
            return {
                'success': False,
                'message': f'设置转速异常: {e}'
            }
    
    def _phase_learning(self) -> Dict[str, Any]:
        """
        @brief 相序学习
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.phase_learning()
            return {
                'success': success,
                'message': '相序学习成功' if success else '相序学习失败'
            }
        except Exception as e:
            logger.error(f"相序学习API异常: {e}")
            return {
                'success': False,
                'message': f'相序学习异常: {e}'
            }
    
    def _reset_system(self) -> Dict[str, Any]:
        """
        @brief 系统复位
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.reset_system()
            return {
                'success': success,
                'message': '系统复位成功' if success else '系统复位失败'
            }
        except Exception as e:
            logger.error(f"系统复位API异常: {e}")
            return {
                'success': False,
                'message': f'系统复位异常: {e}'
            }
    
    # ==================== 便捷控制API ====================
    
    def _move_forward(self) -> Dict[str, Any]:
        """
        @brief 前进
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            speed = data.get('speed', 500)
            
            success = self.motor_api.move_forward(speed)
            return {
                'success': success,
                'message': '前进成功' if success else '前进失败',
                'speed': speed
            }
        except Exception as e:
            logger.error(f"前进API异常: {e}")
            return {
                'success': False,
                'message': f'前进异常: {e}'
            }
    
    def _move_backward(self) -> Dict[str, Any]:
        """
        @brief 后退
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            speed = data.get('speed', 500)
            
            success = self.motor_api.move_backward(speed)
            return {
                'success': success,
                'message': '后退成功' if success else '后退失败',
                'speed': speed
            }
        except Exception as e:
            logger.error(f"后退API异常: {e}")
            return {
                'success': False,
                'message': f'后退异常: {e}'
            }
    
    def _turn_left(self) -> Dict[str, Any]:
        """
        @brief 左转
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            speed = data.get('speed', 500)
            
            success = self.motor_api.turn_left(speed)
            return {
                'success': success,
                'message': '左转成功' if success else '左转失败',
                'speed': speed
            }
        except Exception as e:
            logger.error(f"左转API异常: {e}")
            return {
                'success': False,
                'message': f'左转异常: {e}'
            }
    
    def _turn_right(self) -> Dict[str, Any]:
        """
        @brief 右转
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            speed = data.get('speed', 500)
            
            success = self.motor_api.turn_right(speed)
            return {
                'success': success,
                'message': '右转成功' if success else '右转失败',
                'speed': speed
            }
        except Exception as e:
            logger.error(f"右转API异常: {e}")
            return {
                'success': False,
                'message': f'右转异常: {e}'
            }
    
    def _differential_move(self) -> Dict[str, Any]:
        """
        @brief 差速移动
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            left_speed = data.get('left_speed', 0)
            right_speed = data.get('right_speed', 0)
            
            success = self.motor_api.differential_move(left_speed, right_speed)
            return {
                'success': success,
                'message': '差速移动成功' if success else '差速移动失败',
                'left_speed': left_speed,
                'right_speed': right_speed
            }
        except Exception as e:
            logger.error(f"差速移动API异常: {e}")
            return {
                'success': False,
                'message': f'差速移动异常: {e}'
            }
    
    # ==================== 监控管理API ====================
    
    def _start_monitoring(self) -> Dict[str, Any]:
        """
        @brief 开始监控
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.start_monitoring()
            return {
                'success': success,
                'message': '监控启动成功' if success else '监控启动失败',
                'monitoring': self.motor_api.is_monitoring()
            }
        except Exception as e:
            logger.error(f"启动监控API异常: {e}")
            return {
                'success': False,
                'message': f'启动监控异常: {e}'
            }
    
    def _stop_monitoring(self) -> Dict[str, Any]:
        """
        @brief 停止监控
        @return Dict[str, Any] API响应
        """
        try:
            self.motor_api.stop_monitoring()
            return {
                'success': True,
                'message': '监控停止成功',
                'monitoring': False
            }
        except Exception as e:
            logger.error(f"停止监控API异常: {e}")
            return {
                'success': False,
                'message': f'停止监控异常: {e}'
            }
    
    def _get_monitor_status(self) -> Dict[str, Any]:
        """
        @brief 获取监控状态
        @return Dict[str, Any] API响应
        """
        try:
            return {
                'success': True,
                'monitoring': self.motor_api.is_monitoring(),
                'logging': self.motor_api.is_logging()
            }
        except Exception as e:
            logger.error(f"获取监控状态API异常: {e}")
            return {
                'success': False,
                'message': f'获取监控状态异常: {e}'
            }
    
    # ==================== 数据记录API ====================
    
    def _start_logging(self) -> Dict[str, Any]:
        """
        @brief 开始记录
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json() or {}
            log_file = data.get('log_file', 'motor_data.log')
            
            success = self.motor_api.start_logging(log_file)
            return {
                'success': success,
                'message': '数据记录启动成功' if success else '数据记录启动失败',
                'log_file': log_file,
                'logging': self.motor_api.is_logging()
            }
        except Exception as e:
            logger.error(f"启动记录API异常: {e}")
            return {
                'success': False,
                'message': f'启动记录异常: {e}'
            }
    
    def _stop_logging(self) -> Dict[str, Any]:
        """
        @brief 停止记录
        @return Dict[str, Any] API响应
        """
        try:
            self.motor_api.stop_logging()
            return {
                'success': True,
                'message': '数据记录停止成功',
                'logging': False
            }
        except Exception as e:
            logger.error(f"停止记录API异常: {e}")
            return {
                'success': False,
                'message': f'停止记录异常: {e}'
            }
    
    def _get_log_status(self) -> Dict[str, Any]:
        """
        @brief 获取记录状态
        @return Dict[str, Any] API响应
        """
        try:
            return {
                'success': True,
                'logging': self.motor_api.is_logging()
            }
        except Exception as e:
            logger.error(f"获取记录状态API异常: {e}")
            return {
                'success': False,
                'message': f'获取记录状态异常: {e}'
            }
    
    # ==================== 配置管理API ====================
    
    def _serial_config(self) -> Dict[str, Any]:
        """
        @brief 串口配置管理
        @return Dict[str, Any] API响应
        """
        try:
            if request.method == 'GET':
                # 获取串口配置
                config = self.motor_api.get_serial_config()
                return {
                    'success': True,
                    'config': config
                }
            else:
                # 设置串口配置
                data = request.get_json() or {}
                success = self.motor_api.set_serial_config(data)
                return {
                    'success': success,
                    'message': '串口配置设置成功' if success else '串口配置设置失败',
                    'config': data
                }
        except Exception as e:
            logger.error(f"串口配置API异常: {e}")
            return {
                'success': False,
                'message': f'串口配置异常: {e}'
            }
    
    def _motor_config(self) -> Dict[str, Any]:
        """
        @brief 电机配置管理
        @return Dict[str, Any] API响应
        """
        try:
            if request.method == 'GET':
                # 获取电机配置
                config = self.motor_api.get_motor_config()
                return {
                    'success': True,
                    'config': config
                }
            else:
                # 设置电机配置
                data = request.get_json() or {}
                success = self.motor_api.set_motor_config(data)
                return {
                    'success': success,
                    'message': '电机配置设置成功' if success else '电机配置设置失败',
                    'config': data
                }
        except Exception as e:
            logger.error(f"电机配置API异常: {e}")
            return {
                'success': False,
                'message': f'电机配置异常: {e}'
            }
    
    def _save_config(self) -> Dict[str, Any]:
        """
        @brief 保存配置
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.save_config()
            return {
                'success': success,
                'message': '配置保存成功' if success else '配置保存失败'
            }
        except Exception as e:
            logger.error(f"保存配置API异常: {e}")
            return {
                'success': False,
                'message': f'保存配置异常: {e}'
            }
    
    def _load_config(self) -> Dict[str, Any]:
        """
        @brief 加载配置
        @return Dict[str, Any] API响应
        """
        try:
            success = self.motor_api.load_config()
            return {
                'success': success,
                'message': '配置加载成功' if success else '配置加载失败'
            }
        except Exception as e:
            logger.error(f"加载配置API异常: {e}")
            return {
                'success': False,
                'message': f'加载配置异常: {e}'
            }

    def _scan_ports(self) -> Dict[str, Any]:
        """
        @brief 扫描可用串口
        @return Dict[str, Any] API响应
        """
        try:
            import serial.tools.list_ports
            
            # 获取所有可用串口
            ports = []
            for port in serial.tools.list_ports.comports():
                ports.append(port.device)
            
            # 如果没有检测到串口，返回一些常见的端口
            if not ports:
                import platform
                system = platform.system()
                if system == "Windows":
                    ports = ["COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8"]
                else:
                    ports = ["/dev/ttyUSB0", "/dev/ttyUSB1", "/dev/ttyACM0", "/dev/ttyACM1", "/dev/ttyS0", "/dev/ttyS1"]
            
            logger.info(f"扫描到 {len(ports)} 个串口: {ports}")
            
            return {
                'success': True,
                'ports': ports,
                'count': len(ports)
            }
            
        except Exception as e:
            logger.error(f"串口扫描API异常: {e}")
            return {
                'success': False,
                'message': f'串口扫描失败: {e}',
                'ports': []
            }
    
    # ==================== 健康检查API ====================
    
    def _health_check(self) -> Dict[str, Any]:
        """
        @brief 健康检查
        @return Dict[str, Any] API响应
        """
        try:
            return {
                'success': True,
                'message': '服务正常',
                'connected': self.motor_api.is_connected(),
                'monitoring': self.motor_api.is_monitoring(),
                'logging': self.motor_api.is_logging()
            }
        except Exception as e:
            logger.error(f"健康检查API异常: {e}")
            return {
                'success': False,
                'message': f'健康检查异常: {e}'
            }
    
    # ==================== 服务器管理 ====================
    
    def run(self, debug: bool = False) -> None:
        """
        @brief 运行REST API服务器
        @param debug 是否开启调试模式
        """
        try:
            logger.info(f"启动REST API服务器 - {self.host}:{self.port}")
            self.app.run(host=self.host, port=self.port, debug=debug)
        except Exception as e:
            logger.error(f"REST API服务器运行异常: {e}")
    
    def stop(self) -> None:
        """
        @brief 停止REST API服务器
        """
        try:
            self.motor_api.disconnect()
            logger.info("REST API服务器已停止")
        except Exception as e:
            logger.error(f"停止REST API服务器异常: {e}")
    
    def _web_interface(self) -> str:
        """
        @brief 返回Web界面
        @return str HTML页面内容
        """
        try:
            import os
            web_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'web', 'index.html')
            if os.path.exists(web_file):
                with open(web_file, 'r', encoding='utf-8') as f:
                    return f.read()
            else:
                return """
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>无刷电机控制器</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
                        .container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                        h1 { color: #333; text-align: center; }
                        .api-list { margin-top: 30px; }
                        .api-item { background: #f8f9fa; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #007bff; }
                        .method { font-weight: bold; color: #007bff; }
                        .url { font-family: monospace; background: #e9ecef; padding: 2px 6px; border-radius: 3px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <h1>🚀 无刷电机控制器 API</h1>
                        <p>欢迎使用无刷电机控制器REST API服务！</p>
                        
                        <div class="api-list">
                            <h2>主要API接口：</h2>
                            
                            <div class="api-item">
                                <span class="method">GET</span> <span class="url">/api/health</span>
                                <p>健康检查 - 检查服务状态</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">GET</span> <span class="url">/api/status</span>
                                <p>获取系统状态 - 连接状态、电机状态等</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">POST</span> <span class="url">/api/connect</span>
                                <p>连接电机驱动器</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">POST</span> <span class="url">/api/disconnect</span>
                                <p>断开连接</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">POST</span> <span class="url">/api/motor/forward</span>
                                <p>电机前进</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">POST</span> <span class="url">/api/motor/backward</span>
                                <p>电机后退</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">POST</span> <span class="url">/api/motor/stop</span>
                                <p>停止电机</p>
                            </div>
                            
                            <div class="api-item">
                                <span class="method">POST</span> <span class="url">/api/motor/speed</span>
                                <p>设置电机转速 - 需要JSON参数: {"left_speed": 500, "right_speed": 500}</p>
                            </div>
                        </div>
                        
                        <p style="margin-top: 30px; text-align: center; color: #666;">
                            详细API文档请参考: <a href="/doc/接口详情.md">接口详情文档</a>
                        </p>
                    </div>
                </body>
                </html>
                """
        except Exception as e:
            logger.error(f"加载Web界面异常: {e}")
            return f"<h1>错误</h1><p>加载Web界面失败: {e}</p>"

    def _logging_config(self):
        """日志配置接口"""
        try:
            if request.method == 'GET':
                # 获取当前日志配置
                config = self.motor_api.config_manager.get_logging_config()
                return jsonify({
                    "success": True,
                    "data": config
                })
            elif request.method == 'POST':
                # 设置日志配置
                data = request.get_json()
                if not data:
                    return jsonify({"success": False, "error": "无效的JSON数据"}), 400
                
                # 更新日志配置
                self.motor_api.config_manager.set_logging_config(data)
                
                # 重新初始化日志系统
                from core.logging_config import setup_logging
                setup_logging()
                
                return jsonify({
                    "success": True,
                    "message": "日志配置已更新"
                })
        except Exception as e:
            logger.error(f"日志配置API异常: {e}")
            return jsonify({"success": False, "error": str(e)}), 500

    def _get_logging_options(self):
        """获取日志配置选项"""
        try:
            import configparser
            import os
            
            cfg_file = "config/logging_options.cfg"
            if not os.path.exists(cfg_file):
                return jsonify({"success": False, "error": "日志选项配置文件不存在"}), 404
            
            config = configparser.ConfigParser()
            config.read(cfg_file, encoding='utf-8')
            
            options = {
                "log_levels": dict(config['log_levels']) if 'log_levels' in config else {},
                "log_outputs": dict(config['log_outputs']) if 'log_outputs' in config else {},
                "log_formats": dict(config['log_formats']) if 'log_formats' in config else {},
                "file_settings": dict(config['file_settings']) if 'file_settings' in config else {}
            }
            
            return jsonify({
                "success": True,
                "data": options
            })
        except Exception as e:
            logger.error(f"获取日志选项异常: {e}")
            return jsonify({"success": False, "error": str(e)}), 500

    def _test_logging(self):
        """测试日志接口"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({"success": False, "error": "无效的JSON数据"}), 400
            
            message = data.get('message', '测试日志消息')
            level = data.get('level', 'info')
            
            # 根据级别记录日志
            if level == 'debug':
                logger.debug(message)
            elif level == 'info':
                logger.info(message)
            elif level == 'warning':
                logger.warning(message)
            elif level == 'error':
                logger.error(message)
            else:
                logger.info(message)
            
            return jsonify({
                "success": True,
                "message": f"测试日志已记录: {message}"
            })
        except Exception as e:
            logger.error(f"测试日志异常: {e}")
            return jsonify({"success": False, "error": str(e)}), 500
    
    def _send_serial_command(self) -> Dict[str, Any]:
        """
        @brief 发送串口命令
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json()
            command = data.get('command', '')
            
            if not command:
                return jsonify({
                    'success': False,
                    'message': '命令不能为空'
                })
            
            # 通过motor_api发送串口命令
            result = self.motor_api.send_serial_command(command)
            
            return jsonify({
                'success': True,
                'message': '命令发送成功',
                'result': result
            })
        except Exception as e:
            logger.error(f"发送串口命令API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'发送串口命令异常: {e}'
            })
    
    def _receive_serial_data(self) -> Dict[str, Any]:
        """
        @brief 接收串口数据
        @return Dict[str, Any] API响应
        """
        try:
            # 通过motor_api接收串口数据
            data = self.motor_api.receive_serial_data()
            
            return jsonify({
                'success': True,
                'message': '数据接收成功',
                'data': data
            })
        except Exception as e:
            logger.error(f"接收串口数据API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'接收串口数据异常: {e}'
            })
    
    def _start_serial_terminal(self) -> Dict[str, Any]:
        """
        @brief 启动串口终端
        @return Dict[str, Any] API响应
        """
        try:
            # 通过motor_api启动串口终端
            result = self.motor_api.start_serial_terminal()
            
            return jsonify({
                'success': True,
                'message': '串口终端启动成功',
                'result': result
            })
        except Exception as e:
            logger.error(f"启动串口终端API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'启动串口终端异常: {e}'
            })
    
    def _stop_serial_terminal(self) -> Dict[str, Any]:
        """
        @brief 停止串口终端
        @return Dict[str, Any] API响应
        """
        try:
            # 通过motor_api停止串口终端
            result = self.motor_api.stop_serial_terminal()
            
            return jsonify({
                'success': True,
                'message': '串口终端停止成功',
                'result': result
            })
        except Exception as e:
            logger.error(f"停止串口终端API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'停止串口终端异常: {e}'
            })
    
    # ==================== UART串口日志监控相关API方法 ====================
    
    def _connect_uart(self) -> Dict[str, Any]:
        """
        @brief 连接UART串口
        @return Dict[str, Any] API响应
        """
        try:
            result = self.motor_api.connect_uart()
            return jsonify({
                'success': result,
                'message': 'UART串口连接成功' if result else 'UART串口连接失败'
            })
        except Exception as e:
            logger.error(f"连接UART串口API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'连接UART串口异常: {e}'
            })
    
    def _disconnect_uart(self) -> Dict[str, Any]:
        """
        @brief 断开UART串口连接
        @return Dict[str, Any] API响应
        """
        try:
            result = self.motor_api.disconnect_uart()
            return jsonify({
                'success': result,
                'message': 'UART串口断开成功' if result else 'UART串口断开失败'
            })
        except Exception as e:
            logger.error(f"断开UART串口API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'断开UART串口异常: {e}'
            })
    
    def _send_uart_command(self) -> Dict[str, Any]:
        """
        @brief 发送UART命令
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json()
            if not data or 'command' not in data:
                return jsonify({
                    'success': False,
                    'message': '缺少命令参数'
                })
            
            command = data['command']
            result = self.motor_api.send_uart_command(command)
            
            return jsonify({
                'success': True,
                'message': '命令发送成功',
                'result': result
            })
        except Exception as e:
            logger.error(f"发送UART命令API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'发送UART命令异常: {e}'
            })
    
    def _receive_uart_data(self) -> Dict[str, Any]:
        """
        @brief 接收UART数据
        @return Dict[str, Any] API响应
        """
        try:
            data = self.motor_api.receive_uart_data()
            return jsonify({
                'success': True,
                'message': '数据接收成功',
                'data': data
            })
        except Exception as e:
            logger.error(f"接收UART数据API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'接收UART数据异常: {e}'
            })
    
    def _start_uart_monitor(self) -> Dict[str, Any]:
        """
        @brief 启动UART监控
        @return Dict[str, Any] API响应
        """
        try:
            result = self.motor_api.start_uart_monitor()
            return jsonify({
                'success': result,
                'message': 'UART监控启动成功' if result else 'UART监控启动失败'
            })
        except Exception as e:
            logger.error(f"启动UART监控API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'启动UART监控异常: {e}'
            })
    
    def _stop_uart_monitor(self) -> Dict[str, Any]:
        """
        @brief 停止UART监控
        @return Dict[str, Any] API响应
        """
        try:
            result = self.motor_api.stop_uart_monitor()
            return jsonify({
                'success': result,
                'message': 'UART监控停止成功' if result else 'UART监控停止失败'
            })
        except Exception as e:
            logger.error(f"停止UART监控API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'停止UART监控异常: {e}'
            })
    
    def _get_uart_config(self) -> Dict[str, Any]:
        """
        @brief 获取UART配置
        @return Dict[str, Any] API响应
        """
        try:
            config = self.motor_api.get_uart_config()
            return jsonify({
                'success': True,
                'message': 'UART配置获取成功',
                'config': config
            })
        except Exception as e:
            logger.error(f"获取UART配置API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'获取UART配置异常: {e}'
            })
    
    def _set_uart_config(self) -> Dict[str, Any]:
        """
        @brief 设置UART配置
        @return Dict[str, Any] API响应
        """
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    'success': False,
                    'message': '缺少配置数据'
                })
            
            result = self.motor_api.set_uart_config(data)
            return jsonify({
                'success': result,
                'message': 'UART配置设置成功' if result else 'UART配置设置失败'
            })
        except Exception as e:
            logger.error(f"设置UART配置API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'设置UART配置异常: {e}'
            })
    
    def _test_uart_config(self) -> Dict[str, Any]:
        """
        @brief 测试UART配置
        @return Dict[str, Any] API响应
        """
        try:
            result = self.motor_api.test_uart_config()
            return jsonify(result)
        except Exception as e:
            logger.error(f"测试UART配置API异常: {e}")
            return jsonify({
                'success': False,
                'message': f'测试UART配置异常: {e}'
            })
